/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package aplicacion;

import acercade.AcercaDe;
import acercade.DatosAcercaDe;
import acercade.GPL;
import conexion.Conexion;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import java.sql.SQLException;
import javax.swing.JFrame;

/**
 *
 * @author RED
 */
public class Login extends javax.swing.JFrame {

    private final int ANCHO = 246, ALTO = 210;
    private String BD = "mysql";

    public Login() {
        initComponents();
        this.setLocationRelativeTo(null);
        this.setTitle("JHOLA_SQL");
        this.cboBD.removeAllItems();
        this.setBounds(0, 0, ANCHO, ALTO);
        this.setLocationRelativeTo(null);
        colocarIcono();
        tablaBD.setSelectionMode(0);
        inicializarAcercaDe();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        formularioPrincipal = new javax.swing.JFrame();
        jSplitPane1 = new javax.swing.JSplitPane();
        jSplitPane2 = new javax.swing.JSplitPane();
        jScrollPane3 = new javax.swing.JScrollPane();
        txtQuery = new javax.swing.JTextArea();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jScrollPane4 = new javax.swing.JScrollPane();
        tablaBD = new javax.swing.JTable();
        jToolBar6 = new javax.swing.JToolBar();
        error1 = new javax.swing.JLabel();
        jToolBar2 = new javax.swing.JToolBar();
        jToolBar1 = new javax.swing.JToolBar();
        consultar = new javax.swing.JButton();
        btnEjeSeleccion = new javax.swing.JButton();
        btnEjecutarTodo = new javax.swing.JButton();
        cboBD = new javax.swing.JComboBox();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();
        btnAcercaDe = new javax.swing.JMenuItem();
        ayuda = new javax.swing.JFrame();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane5 = new javax.swing.JScrollPane();
        jTextArea2 = new javax.swing.JTextArea();
        jLabel4 = new javax.swing.JLabel();
        btnlog = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        txtnom = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        txtcla = new javax.swing.JPasswordField();

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        formularioPrincipal.setTitle("JHOLA_SQL");

        jSplitPane2.setDividerLocation(300);
        jSplitPane2.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);

        txtQuery.setColumns(20);
        txtQuery.setRows(5);
        jScrollPane3.setViewportView(txtQuery);

        jSplitPane2.setTopComponent(jScrollPane3);

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jTable2.setMaximumSize(new java.awt.Dimension(100, 100));
        jTable2.setRequestFocusEnabled(false);
        jTable2.setRowHeight(12);
        jScrollPane2.setViewportView(jTable2);

        jSplitPane2.setBottomComponent(jScrollPane2);

        jSplitPane1.setRightComponent(jSplitPane2);

        tablaBD.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Bases De Datos"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tablaBD.setMaximumSize(new java.awt.Dimension(100, 100));
        tablaBD.setRowHeight(12);
        tablaBD.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                tablaBDMouseReleased(evt);
            }
        });
        jScrollPane4.setViewportView(tablaBD);
        tablaBD.getColumnModel().getColumn(0).setResizable(false);

        jSplitPane1.setLeftComponent(jScrollPane4);

        jToolBar6.setFloatable(false);
        jToolBar6.setRollover(true);

        jToolBar2.setRollover(true);

        jToolBar1.setRollover(true);

        consultar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/reboot.png"))); // NOI18N
        consultar.setText("Actualizar Lista De BD    ");
        consultar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                consultarActionPerformed(evt);
            }
        });
        jToolBar1.add(consultar);

        btnEjeSeleccion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/1382605968_22932.png"))); // NOI18N
        btnEjeSeleccion.setText("     ");
        btnEjeSeleccion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEjeSeleccionActionPerformed(evt);
            }
        });
        btnEjeSeleccion.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                btnEjeSeleccionKeyReleased(evt);
            }
        });
        jToolBar1.add(btnEjeSeleccion);

        btnEjecutarTodo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/1382606164_youtube.png"))); // NOI18N
        btnEjecutarTodo.setFocusable(false);
        btnEjecutarTodo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnEjecutarTodo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnEjecutarTodo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEjecutarTodoActionPerformed(evt);
            }
        });
        jToolBar1.add(btnEjecutarTodo);

        cboBD.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cboBD.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cboBDActionPerformed(evt);
            }
        });
        jToolBar1.add(cboBD);

        jMenu1.setText("Archivo");

        jMenuItem1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/power_off.png"))); // NOI18N
        jMenuItem1.setText("salir");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuItem3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/cross.png"))); // NOI18N
        jMenuItem3.setText("Cerrar Cesion");
        jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem3ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem3);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Ayuda");

        jMenuItem2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/soporte.gif"))); // NOI18N
        jMenuItem2.setText("Ayuda...");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItem2);

        btnAcercaDe.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/cohete.png"))); // NOI18N
        btnAcercaDe.setText("Acerca de...");
        btnAcercaDe.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAcercaDeActionPerformed(evt);
            }
        });
        jMenu2.add(btnAcercaDe);

        jMenuBar1.add(jMenu2);

        formularioPrincipal.setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout formularioPrincipalLayout = new javax.swing.GroupLayout(formularioPrincipal.getContentPane());
        formularioPrincipal.getContentPane().setLayout(formularioPrincipalLayout);
        formularioPrincipalLayout.setHorizontalGroup(
            formularioPrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(formularioPrincipalLayout.createSequentialGroup()
                .addGap(69, 69, 69)
                .addComponent(jToolBar2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(68, 68, 68)
                .addComponent(error1, javax.swing.GroupLayout.PREFERRED_SIZE, 481, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(formularioPrincipalLayout.createSequentialGroup()
                .addGap(2, 2, 2)
                .addGroup(formularioPrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(formularioPrincipalLayout.createSequentialGroup()
                        .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 701, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jToolBar6, javax.swing.GroupLayout.PREFERRED_SIZE, 617, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1419, Short.MAX_VALUE)))
        );
        formularioPrincipalLayout.setVerticalGroup(
            formularioPrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(formularioPrincipalLayout.createSequentialGroup()
                .addGroup(formularioPrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jToolBar6, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(formularioPrincipalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, formularioPrincipalLayout.createSequentialGroup()
                        .addGap(518, 518, 518)
                        .addComponent(jToolBar2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(30, 30, 30))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, formularioPrincipalLayout.createSequentialGroup()
                        .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 522, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(error1, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jTextArea2.setColumns(20);
        jTextArea2.setRows(5);
        jTextArea2.setText("Algunos comandos utiles para cunsultas Mysql:\n\n  -create database [nombre]; -Crea una base de datos.\n     Ej. create database negocio; -Crea la base de datos negocio.\n  \n  -select * from [tabla]; – Muestra los registros de la tabla.\n     Ej. select * from autos; – Muestra los registros.\n\n  -create table [nombre](dato1,dato2,dato3,primary key(dato1)); -Crea una tabla en la base de datos.\n     Ej. create table auto(id int,nombre varchar(30),primary key(id)); -Crea la tabla y datos especificados.\n\n  -show tables; – Listar todas las tablas de una base de datos.\n    ");
        jScrollPane5.setViewportView(jTextArea2);

        jLabel4.setText("            AYUDA SOBRE CONSULTAS");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addGap(103, 103, 103)
                .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, 726, Short.MAX_VALUE)
                .addGap(71, 71, 71))
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane5)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 268, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.GroupLayout ayudaLayout = new javax.swing.GroupLayout(ayuda.getContentPane());
        ayuda.getContentPane().setLayout(ayudaLayout);
        ayudaLayout.setHorizontalGroup(
            ayudaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        ayudaLayout.setVerticalGroup(
            ayudaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });

        btnlog.setText("Conectar");
        btnlog.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnlogActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Conectar a MySQL"));

        txtnom.setText("root");
        txtnom.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtnomKeyReleased(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel3.setText("Usuario:");

        jTextField1.setText("localhost");
        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextField1KeyReleased(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel2.setText("Contraseña:");

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel1.setText("Servidor:");

        txtcla.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtclaKeyReleased(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 93, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(txtcla, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jTextField1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(txtnom, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtnom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtcla, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnlog, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnlog)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnlogActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnlogActionPerformed
        conectar();
    }//GEN-LAST:event_btnlogActionPerformed

    private void consultarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_consultarActionPerformed
        actualisarlista();
    }//GEN-LAST:event_consultarActionPerformed

    private void btnEjeSeleccionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEjeSeleccionActionPerformed
//        String consulta;
//
//        consulta = txtQuery.getSelectedText();
        
        ejecutar(txtQuery.getSelectedText().split("\\;"));
        this.actualisarlista();
//        String[] consultas = txtQuery.getText().split("\\;");
//       
//        for(String query : consultas){
//            query = cambiar(query);
//            System.out.println("Vuelta");
//            System.out.println(query);
//            ejecutar(query);
//        }
        
//        ejecutar(consulta);
    }//GEN-LAST:event_btnEjeSeleccionActionPerformed

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        System.exit(1);
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void cboBDActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cboBDActionPerformed
        try{
            BD = cboBD.getSelectedItem().toString();
        }catch(NullPointerException ex){
            
        }
    }//GEN-LAST:event_cboBDActionPerformed

    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
        System.out.println("width: " + this.getSize().width);
        System.out.println("Height: " + this.getSize().height);
    }//GEN-LAST:event_formComponentResized

    private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyReleased
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            txtnom.requestFocus();
        }
    }//GEN-LAST:event_jTextField1KeyReleased

    private void txtnomKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtnomKeyReleased
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            txtcla.requestFocus();
        }
    }//GEN-LAST:event_txtnomKeyReleased

    private void txtclaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtclaKeyReleased
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            conectar();
        }
    }//GEN-LAST:event_txtclaKeyReleased

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
         ayuda.setVisible(true);
         ayuda.setBounds(0, 0, 908, 303);
     }//GEN-LAST:event_jMenuItem2ActionPerformed

    private void btnAcercaDeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAcercaDeActionPerformed
       
    }//GEN-LAST:event_btnAcercaDeActionPerformed

    private void tablaBDMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaBDMouseReleased

        int fila = this.tablaBD.getSelectedRow();
        String bd = this.tablaBD.getValueAt(fila, 0).toString();



        cambiarBDEnCombo(bd);





    }//GEN-LAST:event_tablaBDMouseReleased

    private void btnEjeSeleccionKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnEjeSeleccionKeyReleased
        String texto;

        texto = txtQuery.getSelectedText();
        ejecutar(texto);
    }//GEN-LAST:event_btnEjeSeleccionKeyReleased

    private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed

        formularioPrincipal.setVisible(false);
        txtcla.setText("");
        txtnom.setText("");

    }//GEN-LAST:event_jMenuItem3ActionPerformed

    private void btnEjecutarTodoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEjecutarTodoActionPerformed
//      
        ejecutar(txtQuery.getText().split("\\;"));
        this.actualisarlista();
//        String[] consultas = txtQuery.getText().split("\\;");
//
//        for (int i = 0; i < consultas.length; i++) {
//            consultas[i] = cambiar(consultas[i]);
//            System.out.println(consultas[i]);
//            this.ejecutar(consultas[i]);

//            try (Connection conexion = DriverManager.getConnection(
//                    "jdbc:mysql://localhost/" + (String) baseausar.getSelectedItem(), this.txtnom.getText(), this.txtcla.getText())) {
//                Statement s = conexion.createStatement();
//
//
//
//                ResultSet rs = s.executeQuery(consultas[i]);
//                DefaultTableModel modelo = new DefaultTableModel();
//
//                this.jTable2.setModel(modelo);
//                ResultSetMetaData rsMd = rs.getMetaData();
//                int cantidadColumnas = rsMd.getColumnCount();
//
//                for (int r = 0; r <= cantidadColumnas; r++) {
//                    modelo.addColumn(rsMd.getColumnLabel(r));
//
//
//                    while (rs.next()) {
//                        Object[] fila = new Object[cantidadColumnas];
//                        for (int j = 0; j < cantidadColumnas; j++) {
//                            fila[j] = rs.getObject(j + 1);
//                        }
//                        modelo.addRow(fila);
//                    }
//                }
//                this.error1.setText("CONSULTA REALIZADA CON EXITO");
//            } catch (Exception e) {
//                try {
//                    DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
//                    try (Connection conexion = DriverManager.getConnection(
//                            "jdbc:mysql://localhost/" + (String) baseausar.getSelectedItem(), this.txtnom.getText(), this.txtcla.getText())) {
//                        Statement s = conexion.createStatement();
//
//                        s.execute(consultas[i].toString());
//                    }
//
//                } catch (Exception f) {
//
//                    this.error1.setText("ERROR EN LA SINTAXIS DE LA CONSULTA");
//                    JOptionPane.showMessageDialog(null, f, "Error de conexion con jhola " + f.getMessage(), JOptionPane.ERROR_MESSAGE);
//
//
//                }
//            }

//        }
    }//GEN-LAST:event_btnEjecutarTodoActionPerformed

    private void actualisarlista() {

        try {

            DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
            try (Connection conexion = DriverManager.getConnection(
                    "jdbc:mysql://localhost/mysql", this.txtnom.getText(), this.txtcla.getText())) {
                Statement s = conexion.createStatement();



                ResultSet rs = s.executeQuery("show databases");
                DefaultTableModel modelo = new DefaultTableModel();

                this.tablaBD.setModel(modelo);
                ResultSetMetaData rsMd = rs.getMetaData();
                int cantidadColumnas = rsMd.getColumnCount();

                for (int i = 1; i <= cantidadColumnas; i++) {
                    modelo.addColumn(rsMd.getColumnLabel(i));

                }

                
                while (rs.next()) {
                    Object[] fila = new Object[cantidadColumnas];
                    for (int i = 0; i < cantidadColumnas; i++) {
                        fila[i] = rs.getObject(i + 1);
                        cboBD.addItem(rs.getObject(i + 1));
                       
                    }
                    modelo.addRow(fila);
                }
            }
            
            
        } catch (Exception e) {



            JOptionPane.showMessageDialog(null, e, "Error de conexion con jhola " + e.getMessage(), JOptionPane.ERROR_MESSAGE);

        }

    }

    private void ejecutar(String consulta) {
        
        if(consulta.contains("use ")){
            consulta = consulta.trim();
            BD = consulta.split(" ")[1];
            this.cambiarBDEnCombo(BD);
        }
        
        try (Connection conexion = DriverManager.getConnection(
                "jdbc:mysql://localhost/" + BD, this.txtnom.getText(), this.txtcla.getText())) {
            Statement s = conexion.createStatement();

            System.out.println("Consulta a ejecutar: "+consulta);

            ResultSet rs = s.executeQuery(consulta);
            DefaultTableModel modelo = new DefaultTableModel();

            this.jTable2.setModel(modelo);
            ResultSetMetaData rsMd = rs.getMetaData();
            int cantidadColumnas = rsMd.getColumnCount();

            for (int i = 1; i <= cantidadColumnas; i++) {
                modelo.addColumn(rsMd.getColumnLabel(i));
            }
            
            while (rs.next()) {
                Object[] fila = new Object[cantidadColumnas];
                for (int j = 0; j < cantidadColumnas; j++) {
                    fila[j] = rs.getObject(j + 1);
                }
                modelo.addRow(fila);
            }
            this.error1.setText("CONSULTA REALIZADA CON EXITO");
        } catch (Exception e) {
            try {
                DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
                try (Connection conexion = DriverManager.getConnection(
                        "jdbc:mysql://localhost/" + (String) cboBD.getSelectedItem(), this.txtnom.getText(), this.txtcla.getText())) {
                    Statement s = conexion.createStatement();

                    s.execute(consulta);
                }

            } catch (Exception f) {
                /*PROVISORIO*/
                if(!f.getMessage().contains("empty")){
                    this.error1.setText("ERROR EN LA SINTAXIS DE LA CONSULTA");
                    JOptionPane.showMessageDialog(null, f, "Error de conexion con jhola " + f.getMessage(), JOptionPane.ERROR_MESSAGE);
                }else{
                    System.out.println("Error PARA MEJORAR DE EMPTY");
                }
            }
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                System.out.println(info.getName());
                if ("Metal".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
            javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Login().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JFrame ayuda;
    private javax.swing.JMenuItem btnAcercaDe;
    private javax.swing.JButton btnEjeSeleccion;
    private javax.swing.JButton btnEjecutarTodo;
    private javax.swing.JButton btnlog;
    private javax.swing.JComboBox cboBD;
    private javax.swing.JButton consultar;
    private javax.swing.JLabel error1;
    private javax.swing.JFrame formularioPrincipal;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JSplitPane jSplitPane2;
    private javax.swing.JTable jTable2;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextArea jTextArea2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JToolBar jToolBar2;
    private javax.swing.JToolBar jToolBar6;
    private javax.swing.JTable tablaBD;
    private javax.swing.JTextArea txtQuery;
    private javax.swing.JPasswordField txtcla;
    private javax.swing.JTextField txtnom;
    // End of variables declaration//GEN-END:variables

    private void colocarIcono() {
        Image icon = Toolkit.getDefaultToolkit().
                getImage(ClassLoader.getSystemResource("image/mysqlIcon16x16.png"));

        this.setIconImage(icon);
    }

    private void conectar() {
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        try {
            String nombre, clave, direccion, bd;

            nombre = txtnom.getText();
            clave = txtcla.getText();
            direccion = "localhost";
            bd = "mysql";



            Conexion conexion = new Conexion(direccion, bd, nombre, clave);

            conexion.conectar();
            //esta  conectaqdo
//            mensajerror.setVisible(false);

            formularioPrincipal.setVisible(true);
            actualisarlista();

            //el ancho y el alto de la pantalla Tool
            //Dimension pantalla = Toolkit.getDefaultToolkit().getScreenSize();
            //formularioPrincipal.setBounds(0, 0, pantalla.width, pantalla.height);

            formularioPrincipal.setExtendedState(JFrame.MAXIMIZED_BOTH); //atributo estatico, porque
            //no es necesario crear un jframe para llamar a MAXIMIZED_BOTH
////            formularioPrincipal.setLocationRelativeTo(null);
            this.jSplitPane2.setDividerLocation(400);
            this.jSplitPane1.setDividerLocation(300);


        } catch (SQLException ex) {
            //no estas conectado
            //mensajerror.setVisible(true);
            //            this.setBounds(0, 0, 241, 230);
            formularioPrincipal.setVisible(false);
            //this.mensajerror.setText(("Error: "+ex.getMessage()));
            JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage(), "Error al conectar", JOptionPane.ERROR_MESSAGE);

        }
    }

    private void inicializarAcercaDe() {
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        AcercaDe ad = new AcercaDe(new DatosAcercaDe() {
            @Override
            public String getNombreDelPrograma() {
                //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
                return "JHOLA SQL";
            }

            @Override
            public String getdescripcionCortaDelPrograma() {
                //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
                return "Cliente para MySQL hecho en java";
            }

            @Override
            public String getAutor() {
                //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
                return "Patricio Moraga y Carlos Cordova" ;
            }

            @Override
            public String getAno() {
                //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
                return "2013";
            }

            @Override
            public String getEmailDeContacto() {
                //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
                return "patricioalejandro91@gmailcom";
            }

            @Override
            public GPL.Idioma getIdiomaLicencia() {
                //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
                return GPL.Idioma.AMBOS_IDIOMAS;
            }
        });

        ad.addComponent(btnAcercaDe);

    }

    private String cambiar(String palabra) {
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        String st = "";
        for (int i = 0; i < palabra.length(); i++) {
            if (palabra.charAt(i) != '\n' || palabra.charAt(i) != ' ') {
                st = st + palabra.charAt(i);
            }
        }

        return st;
    }

    private void ejecutar(String[] consultas) {
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    
        for(String query : consultas){
            query = cambiar(query);
//            System.out.println("Vuelta");
//            System.out.println(query);
            ejecutar(query);
        }
    }

    private void cambiarBDEnCombo(String bd) {
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        cboBD.setSelectedItem(bd);
    }
}
